﻿using System;
using System.Collections;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Passageways.Modules.Rolodex.Islands.ViewContacts
{
	/// <summary>
	/// Represents the "Manage Contacts" action page.
	/// </summary>
	public partial class ManageContacts : Page
	{
		/// <summary>
		/// Gets the ID of the workgroup of the island instance this action page acts upon.
		/// </summary>
		private string WorkgroupID
		{
			//TODO: ObjectID contains the Island's owner UserID or WorkgroupID - Our Island is only available to WGs
			get { return Request["ObjectID"]; }
		}

		/// <summary>
		/// Invoked when that page is loaded.
		/// </summary>
		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				//TODO: Set the breadcrumb url of the ContactPageHeader to the ReturnUrl
				
				BindCategories();
			}
		}
		
		/// <summary>
		/// Binds the categories to the repeater.
		/// </summary>
		private void BindCategories()
		{
			CategoryCollection categories = Category.Get();

			DataTable categoryTable = new DataTable();
			categoryTable.Columns.Add("ID", typeof(int));
			categoryTable.Columns.Add("Name");

			foreach(Category category in categories)
			{
				if(Contact.GetNumberInCategory(category.ID, WorkgroupID) > 0)
				{
					DataRow categoryRow = categoryTable.NewRow();
					categoryRow["ID"] = category.ID;
					categoryRow["Name"] = category.Name;

					categoryTable.Rows.Add(categoryRow);
				}
			}

			rptrCategories.DataSource = categoryTable;
			rptrCategories.DataBind();
		}

		/// <summary>
		/// Displays the "Add New Contact" panel.
		/// </summary>
		private void ShowAddContact()
		{
			PnlAddContacts.Visible = true;
			PnlEditContact.Visible = false;

			//TODO: Clear the CtrlMessage
		}

		/// <summary>
		/// Displays the "Edit Contact" panel.
		/// </summary>
		private void ShowEditContact()
		{
			PnlAddContacts.Visible = false;
			PnlEditContact.Visible = true;
			
			//TODO: Clear the CtrlMessage
		}

		/// <summary>
		/// Hides the "Add New Contact" and "Edit Contact" panels and only shows the contact grid.
		/// </summary>
		private void HideAddEditContacts()
		{
			PnlAddContacts.Visible = false;
			PnlEditContact.Visible = false;

			BindCategories();
		}

		/// <summary>
		/// Invoked when an item is bound to the repeater. This method will bind contacts in
		/// a categort to the inner data grids.
		/// </summary>
		protected void OnCategoryDataBound(object sender, RepeaterItemEventArgs e)
		{
			HiddenField hdnCategoryID = (HiddenField)e.Item.FindControl("hdnCategoryID");
			DataGrid dgContacts = (DataGrid)e.Item.FindControl("dgContacts");

			int categoryID = int.Parse(hdnCategoryID.Value);

			DataTable contactsTable = new DataTable();
			contactsTable.Columns.Add("ContactID", typeof(int));
			contactsTable.Columns.Add("CompanyName");
			contactsTable.Columns.Add("ContactName");
			contactsTable.Columns.Add("Phone");
			contactsTable.Columns.Add("Email");
			contactsTable.Columns.Add("LastUpdateBy");
			contactsTable.Columns.Add("LastUpdateDateTime", typeof(DateTime));

			ContactCollection contacts = Contact.Get(categoryID, WorkgroupID);

			foreach(Contact contact in contacts)
			{
				DataRow contactRow = contactsTable.NewRow();
				contactRow["ContactID"] = contact.ID.ToString();
				contactRow["CompanyName"] = contact.CompanyName;
				contactRow["ContactName"] = contact.Name;
				contactRow["Email"] = contact.Email;
				contactRow["Phone"] = contact.Phone;
				contactRow["LastUpdateBy"] = contact.LastUpdateBy;
				contactRow["LastUpdateDateTime"] = contact.LastUpdateDateTime;

				contactsTable.Rows.Add(contactRow);
			}

			dgContacts.DataSource = contactsTable;
			dgContacts.DataBind();
		}

		/// <summary>
		/// Invoked when the "Add New Contact" toolbar button is clicked.
		/// </summary>
		protected void OnNewCategoryClick(object sender, EventArgs e)
		{
			txtCompanyName.Text = string.Empty;
			txtPrimaryName.Text = string.Empty;
			txtPrimaryPhone.Text = string.Empty;
			txtPrimaryEmail.Text = string.Empty;
			txtWebsite.Text = string.Empty;
			txtAddress1.Text = string.Empty;
			txtAddress2.Text = string.Empty;
			txtCity.Text = string.Empty;
			txtState.Text = string.Empty;
			txtZip.Text = string.Empty;
			txtNotes.Text = string.Empty;
			
			ddlCategories.Items.Clear();

			ListItem li = new ListItem("- Select -", string.Empty);
			li.Selected = true;

			ddlCategories.Items.Add(li);

			foreach(Category c in Category.Get())
			{
				li = new ListItem(c.Name, c.ID.ToString());
				ddlCategories.Items.Add(li);
			}

			ShowAddContact();
		}

		/// <summary>
		/// Invoked when the "OK" button is clicked on the "Add New Contact" panel.
		/// </summary>
		protected void OnAddContactOkClick(object sender, EventArgs e)
		{
			string companyName = txtCompanyName.Text.Trim();

			if(string.IsNullOrEmpty(companyName))
			{
				//TODO: Show a Warning in CtrlMessage with the text "Company Name is required"
				return;
			}

			string primaryName = txtPrimaryName.Text.Trim();

			if(string.IsNullOrEmpty(primaryName))
			{
				//TODO: Show a Warning in CtrlMessage with the text "Primary Contact Name is required"
				return;
			}

			string phone = txtPrimaryPhone.Text.Trim();

			if(string.IsNullOrEmpty(phone))
			{
				//TODO: Show a Warning in CtrlMessage with the text "Primary Contact Phone is required"
				return;
			}

			string email = txtPrimaryEmail.Text.Trim();

			if(string.IsNullOrEmpty(email))
			{
				//TODO: Show a Warning in CtrlMessage with the text "Primary Contact Email is required"
				return;
			}

			int categoryID;

			if(!int.TryParse(ddlCategories.SelectedValue, out categoryID))
			{
				//TODO: Show a Warning in CtrlMessage with the text "Please select the category you want this contact added to."
				return;
			}

			Address address = new Address();
			address.AddressLine1 = txtAddress1.Text.Trim();
			address.AddressLine2 = txtAddress2.Text.Trim();
			address.City = txtCity.Text.Trim();
			address.State = txtState.Text.Trim();
			address.Zip = txtZip.Text.Trim();

			Contact.Add(categoryID, WorkgroupID, companyName, primaryName, phone, address, txtFax.Text.Trim(), email, txtNotes.Text, txtWebsite.Text.Trim());

			//TODO: Show success message "Contact added successfully" in CtrlMessage

			// send alert to workgroup users
			ArrayList userIDs = new ArrayList();
			//TODO: Get a collection of users in the Workgrouop

			//TODO: Loop through each user and store the userID in our Array List - exclude current user

			string fromEmail = ""; //TODO: Get the current user's email
			string subject = "Rolodex Contact Added";
			string body = string.Format("The contact for company, '{0}', has been added.", companyName);
			//TODO: Send an alert item to the users

			HideAddEditContacts();
		}

		/// <summary>
		/// Invoked when the "Cancel" button is clicked on the "Add New Contact" panel.
		/// </summary>
		protected void OnAddContactCancelClick(object sender, EventArgs e)
		{
			HideAddEditContacts();
		}

		/// <summary>
		/// Invoked when the "OK" button is clicked on the "Edit Contact" panel.
		/// </summary>
		protected void OnEditContactOkClick(object sender, EventArgs e)
		{
			string companyName = txtEditCompanyName.Text.Trim();

			if(string.IsNullOrEmpty(companyName))
			{
				//TODO: Show a Warning in CtrlMessage "Company Name is required"
				return;
			}

			string primaryName = txtEditPrimaryName.Text.Trim();

			if(string.IsNullOrEmpty(primaryName))
			{
				//TODO: Show a Warning "Primary Contact Name is required"
				return;
			}

			string phone = txtEditPrimaryPhone.Text.Trim();

			if(string.IsNullOrEmpty(phone))
			{
				//TODO: Show a Warning "Primary Contact Phone is required"
				return;
			}

			string email = txtEditPrimaryEmail.Text.Trim();

			if(string.IsNullOrEmpty(email))
			{
				//TODO: Show a Warning "Primary Contact Email is required"
				return;
			}

			int categoryID;

			if(!int.TryParse(ddlEditContactCategory.SelectedValue, out categoryID))
			{
				//TODO: Show a Warning "Please select the category you want this contact added to."
				return;
			}

			int contactID = (int)ViewState["EditContactID"];

			Contact contact = new Contact(contactID);
			contact.Address.AddressLine1 = txtEditAddress1.Text.Trim();
			contact.Address.AddressLine2 = txtEditAddress2.Text.Trim();
			contact.Address.City = txtEditCity.Text.Trim();
			contact.Address.State = txtEditState.Text.Trim();
			contact.Address.Zip = txtEditZip.Text.Trim();
			contact.CompanyName = companyName;
			contact.Email = email;
			contact.Name = primaryName;
			contact.Notes = txtEditNotes.Text;
			contact.Phone = phone;
			contact.Website = txtEditWebsite.Text.Trim();
			contact.CategoryID = int.Parse(ddlEditContactCategory.SelectedValue);
			contact.Update();

			//TODO: Show a Success message "Contact updated successfully"

			// send alert to workgroup users
			ArrayList userIDs = new ArrayList();
			//TODO: Get a collection of users in this workgroup

			//TODO: Loop over the users, store the userIDs in the ArrayList - exclude current user

			string fromEmail = ""; //TODO: Get current user's email
			string subject = "Rolodex Contact Changed";
			string body = string.Format("The contact for company, '{0}', has been changed.", companyName);

			//TODO: Send an alert item

			HideAddEditContacts();
		}

		/// <summary>
		/// Invoked when the "Cancel" button is clicked on the "Edit Contact" panel.
		/// </summary>
		protected void OnEditContactCancelClick(object sender, EventArgs e)
		{
			HideAddEditContacts();
		}

		/// <summary>
		/// Invoked when the "Delete" button on the data grid is clicked.
		/// </summary>
		protected void OnContactDeleteClick(object sender, DataGridCommandEventArgs e)
		{
			int contactID = int.Parse(((DataGrid)e.Item.Parent.Parent).DataKeys[e.Item.ItemIndex].ToString());
			Contact deleteMe = new Contact(contactID);

			Contact.Remove(contactID);

			// send alert to workgroup users
			ArrayList userIDs = new ArrayList();
			//TODO: Get a collection of users in this workgroup

			//TODO: Loop over the users, store the userIDs in the ArrayList - exclude current user

			string fromEmail = ""; //TODO: Get current user's email
			string subject = "Rolodex Contact Deleted";
			string body = string.Format("The contact for company, '{0}', has been deleted.", deleteMe.CompanyName);

			//TODO: Send an alert item

			BindCategories();
		}

		/// <summary>
		/// Invoked when the "Edit" button on the data grid is clicked.
		/// </summary>
		protected void OnContactEditClick(object sender, DataGridCommandEventArgs e)
		{
			int contactID = int.Parse(((DataGrid)e.Item.Parent.Parent).DataKeys[e.Item.ItemIndex].ToString());
			
			ViewState["EditContactID"] = contactID;

			Contact c = new Contact(contactID);

			txtEditAddress1.Text = c.Address.AddressLine1;
			txtEditAddress2.Text = c.Address.AddressLine2;
			txtEditCity.Text = c.Address.City;
			txtEditCompanyName.Text = c.CompanyName;
			txtEditNotes.Text = c.Notes;
			txtEditPrimaryEmail.Text = c.Email;
			txtEditPrimaryName.Text = c.Name;
			txtEditPrimaryPhone.Text = c.Phone;
			txtEditState.Text = c.Address.State;
			txtEditWebsite.Text = c.Website;
			txtEditZip.Text = c.Address.Zip;

			ddlEditContactCategory.Items.Clear();

			ListItem li = null;

			foreach(Category cat in Category.Get())
			{
				li = new ListItem(cat.Name, cat.ID.ToString());

				if(c.CategoryID.Equals(cat.ID))
				{
					li.Selected = true;
				}
				
				ddlEditContactCategory.Items.Add(li);
			}

			ShowEditContact();
		}
	}
}